<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Series;
use App\Services\SeriesService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * API 系列控制器
 * 
 * 职责：
 * - 处理系列相关的API请求
 * - 用于文章编辑页面选择/创建系列
 */
class SeriesController extends Controller
{
    /**
     * 系列服务
     * 
     * @var SeriesService
     */
    protected SeriesService $seriesService;

    /**
     * 构造器
     */
    public function __construct(SeriesService $seriesService)
    {
        $this->seriesService = $seriesService;
    }

    /**
     * 获取所有系列列表（用于下拉选择）
     */
    public function index(Request $request)
    {
        $query = Series::with('author')
            ->orderBy('name');

        // 搜索过滤
        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        $series = $query->get()->map(function($s) {
            return [
                'id' => $s->id,
                'name' => $s->name,
                'slug' => $s->slug,
                'description' => $s->description,
                'post_count' => $s->post_count,
            ];
        });

        return response()->json($series);
    }

    /**
     * 创建新系列（从文章编辑页面）
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:series,slug',
            'description' => 'nullable|string',
            'featured_image' => 'nullable|string',
            'is_visible' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => '验证失败',
                'errors' => $validator->errors(),
            ], 422);
        }

        $user = auth()->user();
        if (!$user) {
            return response()->json(['message' => '未授权'], 401);
        }

        $series = $this->seriesService->create($request->all(), $user);

        return response()->json([
            'message' => '系列创建成功',
            'series' => [
                'id' => $series->id,
                'name' => $series->name,
                'slug' => $series->slug,
                'description' => $series->description,
                'post_count' => $series->post_count,
            ],
        ], 201);
    }

    /**
     * 获取系列详情
     */
    public function show(Series $series)
    {
        $series->load('author');

        // 获取系列文章（根据 sort_mode 排序，包括草稿）
        $posts = $this->seriesService->getPosts($series, ['include_drafts' => true]);

        return response()->json([
            'id' => $series->id,
            'name' => $series->name,
            'slug' => $series->slug,
            'description' => $series->description,
            'featured_image' => $series->featured_image,
            'post_count' => $series->post_count,
            'is_visible' => $series->is_visible,
            'author' => [
                'id' => $series->author->id,
                'name' => $series->author->name,
            ],
            'posts' => $posts->map(function($post) {
                return [
                    'id' => $post->id,
                    'title' => $post->title,
                    'slug' => $post->slug,
                    'published_at' => $post->published_at?->format('Y-m-d H:i:s'),
                    'series_order' => $post->series_order,
                    'sort_mode' => $post->sort_mode,
                ];
            }),
        ]);
    }

    /**
     * 更新系列
     */
    public function update(Request $request, Series $series)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|string|max:255',
            'slug' => 'nullable|string|max:255|unique:series,slug,' . $series->id,
            'description' => 'nullable|string',
            'featured_image' => 'nullable|string',
            'is_visible' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => '验证失败',
                'errors' => $validator->errors(),
            ], 422);
        }

        $series = $this->seriesService->update($series, $request->all());

        return response()->json([
            'message' => '系列更新成功',
            'series' => [
                'id' => $series->id,
                'name' => $series->name,
                'slug' => $series->slug,
                'description' => $series->description,
                'post_count' => $series->post_count,
            ],
        ]);
    }

    /**
     * 更新系列内文章顺序
     */
    public function updateOrder(Request $request, Series $series)
    {
        $validator = Validator::make($request->all(), [
            'post_orders' => 'required|array',
            'post_orders.*' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => '验证失败',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $this->seriesService->updatePostOrder($series, $request->input('post_orders'));

            return response()->json([
                'message' => '文章顺序更新成功',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    /**
     * 更新排序模式
     */
    public function updateSortMode(Request $request, Series $series)
    {
        $validator = Validator::make($request->all(), [
            'sort_mode' => 'required|in:manual,published_at',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => '验证失败',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $this->seriesService->updateSortMode($series, $request->input('sort_mode'));

            return response()->json([
                'message' => '排序模式更新成功',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}
